//
//  ZXY_CricleFlipBtnView.m
//  CircleBtnFrame
//
//  Created by ZXYStart on 15/10/15.
//  Copyright © 2015年 宇周. All rights reserved.
//

#import "ZXY_CricleFlipBtnView.h"
#import <QuartzCore/QuartzCore.h>
@interface ZXY_CricleFlipBtnView()


@end

@implementation ZXY_CricleFlipBtnView

- (id)init
{
    if(self = [super init])
    {
        [self initMethod];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    if(self = [super initWithFrame:frame])
    {
        [self initMethod];
    }
    return self;
}

#pragma mark -
#pragma mark 初始化方法
/**
 *  初始化方法
 */
- (void)initMethod
{
    self.itemSize = 60;
    self.tagStart = 1000;
    self.isAnimation = YES;
    self.radius = 100;
    self.itemsCircleCenter = CGPointMake(CGRectGetMidX(self.frame), CGRectGetMidY(self.frame) - 50);
}

#pragma mark -
#pragma mark 显示与隐藏
/**
 *  显示flipView
 */
- (void)showFlipBtns:(UIView *)superView
{
    if([superView.subviews containsObject:self])
    {
        return;
    }
    [superView addSubview:self];
    [self changeImgToBtns];
    [self startInitCircleLayout];
}

/**
 *  隐藏flipView
 */
- (void)hideFlipBtns
{
    for(UIButton *one in self.btns)
    {
        [one removeFromSuperview];
    }
    [self.btns removeAllObjects];
    [self removeFromSuperview];
}

/**
 *  按钮点击事件
 *
 *  @param btn 按钮
 */
- (void)flipBtnClick:(UIButton *)btn
{
    if(self.delegate)
    {
        [self.delegate clickCricleFlipBtnView:self BtnAtIndex:btn.tag - self.tagStart];
    }
    [self functionForHideWithClickTag:btn.tag];
}

- (void)functionForHideWithClickTag:(NSInteger)tag
{
    UIButton *selectBtn = (UIButton *)[self viewWithTag:tag];
    CGFloat endPointX   = selectBtn.center.x;
    CGFloat endPointY   = selectBtn.center.y;
    
    CGFloat centerX = self.itemsCircleCenter.x;
    CGFloat centerY = self.itemsCircleCenter.y;
    CGFloat begainPointX = centerX + self.radius;
    CGFloat begainPointY = centerY;
    for(int i = 0 ; i < self.btns.count ; i++)
    {
        UIButton *current = [self.btns objectAtIndex:i];
        CGPoint  begainCenter = CGPointMake(current.center.x, current.center.y);
        current.center = selectBtn.center;
        [current.layer addAnimation:[self addAnimationToFlipBtn:begainCenter
                                                    andEndPoint:CGPointMake(endPointX, endPointY)
                                                    andStartPoint:CGPointMake(begainPointX, begainPointY)isHide:YES]
                                                    forKey:@"position"];
    }
}


#pragma mark -
#pragma mark 按钮群操作
/**
 *  将 imgs的图片分布到 btns
 */
- (void)changeImgToBtns
{
    if(self.imgs == nil && self.btns.count == 0 ) //都为空的情况下抛出异常
    {
        NSException *except = [NSException exceptionWithName:@"NullArrayBtns" reason:@"ZXY_CricleFlipBtnView.h 文件初始化buttons 时出现错误，错误为： imgs 和 btns都为空" userInfo:nil];
        @throw except;
    }
    
    if(self.delegate == nil) //代理不能为空
    {
        NSException *except = [NSException exceptionWithName:@"NullArrayBtns" reason:@"ZXY_CricleFlipBtnView.h 代理不能为空" userInfo:nil];
        @throw except;
    }
    
    self.btns = [[NSMutableArray alloc] init];
    for(int i = 0 ; i < self.imgs.count ; i++)
    {
        NSString *imgName = self.imgs[i];                    //取出对应index中的图片名称
        UIButton *oneBtn  = [[UIButton alloc] initWithFrame:
                             CGRectMake(0, 0, self.itemSize, self.itemSize)
                             ];                              //初始化button
        oneBtn.layer.cornerRadius  = self.itemSize / 2.0;    //圆角设置
        oneBtn.layer.masksToBounds = YES;
        oneBtn.tag                 = self.tagStart + i;      //设置tag
        [oneBtn setImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];//设置button的图片
        [oneBtn addTarget:self action:@selector(flipBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.btns addObject:oneBtn];                       //btns中增加这个新的button
    }
}

/**
 *  初始化 圆形布局
 */
- (void)startInitCircleLayout
{
    CGFloat centerX = self.itemsCircleCenter.x;
    CGFloat centerY = self.itemsCircleCenter.y;
    CGFloat begainPointX = centerX + self.radius;
    CGFloat begainPointY = centerY;
    for(int i = 0 ; i < self.btns.count ; i++)
    {
        UIButton *current = self.btns[i];
        CGFloat  itemCenterX = centerX + self.radius * cos(M_PI * 2 * i/ self.btns.count);
        CGFloat  itemCenterY = centerY + self.radius * sin(M_PI * 2 * i/ self.btns.count);
        current.center = CGPointMake(itemCenterX,itemCenterY );
        [self addSubview:current];
        [current.layer addAnimation:[self addAnimationToFlipBtn:CGPointMake(begainPointX, begainPointY) andEndPoint:CGPointMake(itemCenterX, itemCenterY) andStartPoint:CGPointMake(begainPointX, begainPointY) isHide:NO] forKey:@"position"];
    }
}

/**
 *  用于btns的初始动画效果
 *
 *  @param begainPoint 起点位置
 *  @param endPoint    终点位置
 *
 *  @return 返回动画
 */
- (CAAnimation *)addAnimationToFlipBtn:(CGPoint)begainPoint andEndPoint:(CGPoint)endPoint andStartPoint:(CGPoint)startPoint isHide:(BOOL)isHidden
{
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animation];
    CGMutablePathRef path          = CGPathCreateMutable();//获取path
    CGPathMoveToPoint(path, NULL, begainPoint.x, begainPoint.y);//path移动至初始点
    CGFloat degreeEnd   = [self degreeOfPoint:endPoint andEndPoint:startPoint withRadius:self.radius];//获取角度
    CGFloat degreeStart = [self degreeOfPoint:begainPoint andEndPoint:startPoint withRadius:self.radius];
    CGPathAddArc(path, nil, self.itemsCircleCenter.x,
                            self.itemsCircleCenter.y,
                            self.radius, degreeStart , degreeEnd, false);//为path增加圆弧
    animation.path = path;
    CGPathRelease(path);    //释放path
    animation.duration = 0.2;
    animation.repeatCount = 1;
    animation.calculationMode = @"cubicPaced";
    __weak ZXY_CricleFlipBtnView *weakSelf = self;
    if(isHidden)
    {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf hideFlipBtns];
        });
    }
    return animation;
}

- (CGFloat)degreeOfPoint:(CGPoint)begainPoint andEndPoint:(CGPoint)endPoint withRadius:(CGFloat)radius
{
    CGFloat deltaX = endPoint.x - begainPoint.x; //获取两点x的间距
    CGFloat deltaY = endPoint.y - begainPoint.y; //获取两点y的间距
    CGFloat distanceOF = sqrt(pow((begainPoint.x - endPoint.x), 2) +
                              pow((begainPoint.y - endPoint.y), 2)); //获取两点的间距
    CGFloat angle  = acos((radius * 2 * radius - distanceOF * distanceOF) /
                          (2 * radius * radius));//获取两点与圆心的夹角
    //第一象限 夹角应为 2pi - 角度
    if(deltaX > 0 && deltaY > 0)
    {
        return M_PI * 2 - angle;
    }
    //第二象限 夹角应为 2pi - 角度
    else if (deltaX < 0 && deltaY > 0)
    {
        return M_PI * 2 - angle;
    }
    //第三、四象限 夹角应为 角度
    else if (deltaX < 0 && deltaY < 0)
    {
        return angle;
    }
    else
    {
        return angle;
    }
}

@end
